package com.maple.action;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;
@ResultPath("/")
@Results(value={
        @Result(name="success", type="stream",params={"contentType","application/octet-stream;charset=utf-8","inputName","inputStream","contentDisposition","attachment;filename=${fileName}","bufferSize","4096"})
})
public class DownloadAction extends ActionSupport {
    private String fileName;
    private InputStream inputStream;
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public InputStream getInputStream() {
        InputStream tempInputStream= (InputStream) ServletActionContext.getRequest().getAttribute("inputStream");
        String tempFileName= (String) ServletActionContext.getRequest().getAttribute("fileName");
        this.setFileName(tempFileName);
        return tempInputStream;
    }

    public String getFileName() {
        String temp=this.fileName;
        {        
            try {
                this.fileName =  new String(temp.getBytes(), "ISO8859-1"); 
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }   
        }
        return fileName;
    }
}


//使用方法
/*public class DemoAction extends ActionSupport {
    //通过在params中配置namespace参数，就可以改变action的命名空间
    @Action(value="downloadDemo",results={@Result(name="downloadDemo", type="chain",params={"namespace","/","actionName","download"}})
    public String downloadDemo() throws FileNotFoundException
    {
        InputStream inputStream=new FileInputStream(new File("c:/test.xls")) ;
        ServletActionContext.getRequest().setAttribute("inputStream", inputStream);
        ServletActionContext.getRequest().setAttribute("fileName", "中文test.xls");
        return "downloadDemo";
    }
}

http://localhost:8080/wang/downloadDemo.action*/